<template>
  <div class="graph-editor">
    <div class="toolbar">
      <button @click="addNumberNode">添加数字节点</button>
      <button @click="addMathNode">添加数学节点</button>
      <button @click="addStringNode">添加字符串节点</button>
    </div>
    <canvas ref="canvas" id="graphCanvas"></canvas>
  </div>
</template>

<script>
import { LGraph, LGraphCanvas, LiteGraph } from 'litegraph.js'
import 'litegraph.js/css/litegraph.css'

export default {
  name: 'LiteGraphEditor',
  data() {
    return {
      graph: null,
      canvas: null
    }
  },
  mounted() {
    this.initGraph()
    
    // 注册自定义节点
    LiteGraph.registerNodeType("custom/myNode", {
      title: "自定义节点",
      inputs: [["输入", "number"]],
      outputs: [["输出", "number"]],
      properties: { value: 1 },
      
      onExecute: function() {
        this.setOutputData(0, this.properties.value * 2)
      }
    })
  },
  methods: {
    initGraph() {
      // 初始化图形
      this.graph = new LGraph()
      
      // 初始化画布
      const canvasElement = this.$refs.canvas
      this.canvas = new LGraphCanvas(canvasElement, this.graph)
      
      // 设置画布大小
      this.canvas.resize(window.innerWidth, window.innerHeight - 50)
      
      // 开始运行
      this.graph.start()
    },
    
    addNumberNode() {
      const node = LiteGraph.createNode("basic/number")
      node.pos = [Math.random() * 500, Math.random() * 300]
      this.graph.add(node)
    },
    
    addMathNode() {
      const node = LiteGraph.createNode("math/operation")
      node.pos = [Math.random() * 500, Math.random() * 300]
      this.graph.add(node)
    },
    
    addStringNode() {
      const node = LiteGraph.createNode("basic/string")
      node.pos = [Math.random() * 500, Math.random() * 300]
      this.graph.add(node)
    }
  }
}
</script>

<style scoped>
.graph-editor {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.toolbar {
  padding: 10px;
  background-color: #f0f0f0;
}

button {
  margin-right: 10px;
  padding: 5px 10px;
}

canvas {
  flex: 1;
}
</style> 